package com.anyonavinfo.cpaddemo.view.mainview;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;

import com.anyonavinfo.cpaddemo.view.mainview.applist.AppListView;
import com.anyonavinfo.cpaddemo.view.mainview.homepage.HomePageView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZuiC on 2017/1/22.
 */

public class MainViewPager extends ViewPager {

    private List<View> mViewList = new ArrayList<>();
    private ViewPagerAdapter mViewPagerAdapter;
    private Context mContext;

    public MainViewPager(Context context) {
        super(context);
        this.mContext = context;
        mViewList.add(new HomePageView(context));
    }

    public MainViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        mViewList.add(new HomePageView(context));
    }

    public boolean onBackPressed(){
        boolean result = true;
        for (int i = 0; i < mViewList.size() - 1; i++){
            if (!((AppListView)mViewList.get(i + 1)).onBackPressed()){
                result = false;
            }
        }
        return result;
    }

<<<<<<< HEAD
    public void onRedisplay(){
        ((HomePageView)mViewList.get(0)).onRedisplay();
    }

=======
>>>>>>> b56716b621890f59100a220d4c7abe0ddb29e232
    public void updatePageSize(int size){
        if (mViewPagerAdapter == null){
            for (int i = 0; i < size - 1; i++){
                mViewList.add(new AppListView(mContext));
            }
            mViewPagerAdapter = new ViewPagerAdapter();
            setAdapter(mViewPagerAdapter);
        }else {
            List<View> temp = new ArrayList<>();
            temp.add(mViewList.get(0));
            for (int i = 0; i < size - 1; i++){
                if (mViewList.get(i + 1) == null){
                    temp.add(mViewList.get(i + 1));
                }else {
                    temp.add(new AppListView(mContext));
                }
            }
            mViewList.clear();
            mViewList = temp;
            mViewPagerAdapter.notifyDataSetChanged();
        }
    }

    private class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mViewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(View view, int position)                                //实例化Item
        {
            ((ViewPager) view).addView(mViewList.get(position), 0);
            return mViewList.get(position);
        }
    }
}


